<template>
  <div class="gen-page">
    <!-- 搜索和操作区域 -->
    <div class="page-header bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h1 class="text-xl font-bold text-gray-800">代码生成器</h1>
          <p class="text-sm text-gray-600 mt-1">管理数据库表的代码生成配置</p>
        </div>
        <div class="flex items-center space-x-3">
          <el-button type="primary" :icon="Plus" @click="addDialogVisible = true">
            添加表
          </el-button>
          <el-button :icon="Refresh" @click="load">
            刷新
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="search-form-inline">
          <el-form-item label="表名" class="search-form-item">
            <el-input
              v-model="searchForm.tableName"
              placeholder="请输入表名"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-table"></i>
              </template>
            </el-input>
      </el-form-item>
          <el-form-item label="注释" class="search-form-item">
            <el-input
              v-model="searchForm.comment"
              placeholder="请输入表注释"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-comment"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="模块" class="search-form-item">
            <el-input
              v-model="searchForm.moduleName"
              placeholder="请输入模块名"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-cubes"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="search-form-buttons">
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
      </el-form-item>
    </el-form>
      </div>
    </div>

    <!-- 批量操作工具栏 -->
    <div v-if="selection.length > 0" class="batch-toolbar bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <span class="text-primary font-medium">已选择 {{ selection.length }} 项</span>
          <div class="flex items-center space-x-2">
            <el-button type="danger" size="small" @click="batchRemove">
              <i class="fas fa-trash mr-1"></i>
              批量删除
            </el-button>
            <el-button type="info" size="small" @click="doBatchPreview">
              <i class="fas fa-eye mr-1"></i>
              批量预览
            </el-button>
            <el-button type="warning" size="small" @click="doBatchGenerate">
              <i class="fas fa-code mr-1"></i>
              批量生成
            </el-button>
          </div>
        </div>
        <el-button size="small" @click="selection = []">
          取消选择
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <SystemTable
      title="数据表列表"
      :data="rows"
      :total="total"
      v-loading="loading"
      @page-change="handlePageChange"
      @selection-change="onSelChange"
      @refresh="load"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="tableName" label="表名" min-width="150" show-overflow-tooltip />
      <el-table-column prop="comment" label="注释" min-width="200" show-overflow-tooltip />
      <el-table-column prop="moduleName" label="模块" width="120" show-overflow-tooltip />
      <el-table-column prop="entityName" label="实体名" width="120" show-overflow-tooltip />
      <el-table-column prop="permissionPrefix" label="权限前缀" min-width="180" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="160" show-overflow-tooltip />
      <el-table-column label="操作" width="480" align="center" fixed="right">
        <template #default="{ row }">
          <div class="table-actions">
            <el-button size="small" type="primary" @click="openDrawer(row)">
              <i class="fas fa-cog mr-1"></i>
              配置
            </el-button>
            <el-button size="small" type="info" @click="doPreview(row)">
              <i class="fas fa-eye mr-1"></i>
              预览
            </el-button>
            <el-dropdown size="small" trigger="click">
            <el-button size="small" type="success">
                <i class="fas fa-code mr-1"></i>
                生成代码
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                  <el-dropdown-item @click="executeGenerate(row)">
                    <i class="fas fa-download mr-2"></i>
                    生成到输出目录
                  </el-dropdown-item>
                  <el-dropdown-item @click="generateToProject(row)">
                    <i class="fas fa-folder-open mr-2"></i>
                    生成到项目模块
                  </el-dropdown-item>
                  <el-dropdown-item @click="downloadZip(row)">
                    <i class="fas fa-file-archive mr-2"></i>
                    下载压缩包
                  </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
            <el-button size="small" type="warning" @click="openEdit(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="remove(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </SystemTable>

    <el-dialog v-model="dialogVisible" title="生成预览" width="90vw">
      <el-tabs v-model="activePreviewTab" type="card">
        <el-tab-pane
          v-for="(f, idx) in previewFiles"
          :key="idx"
          :label="fileLabel(f)"
          :name="String(idx)"
        >
          <el-alert :title="f.type" type="info" show-icon class="mb-2" />
          <el-scrollbar max-height="75vh">
            <pre class="whitespace-pre-wrap text-sm">{{ f.content }}</pre>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="dialogVisible=false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="addDialogVisible" title="新增生成表" width="480px">
      <el-form label-width="100px">
        <el-form-item label="表名">
          <el-select v-model="selectedTableName" placeholder="选择现有表" filterable clearable :loading="loadingTables" style="width: 300px">
            <el-option v-for="n in dbTableOptions" :key="n" :label="n" :value="n" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="confirmAdding" @click="confirmAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 全屏配置弹窗 -->
    <el-dialog
      v-model="drawerVisible"
      :title="drawerTitle"
      fullscreen
      destroy-on-close
      class="gen-config-dialog"
    >
      <!-- 弹窗头部操作栏 -->
      <template #header>
        <div class="config-header flex items-center justify-between w-full pr-10">
          <div class="header-left flex items-center">
            <h2 class="text-xl font-bold text-gray-800">{{ drawerTitle }}</h2>
            <el-tag class="ml-3" type="info" size="small">{{ currentRecord?.tableName }}</el-tag>
          </div>
          <div class="header-actions flex items-center space-x-3">
            <el-button
              type="success"
              :icon="Refresh"
              :disabled="!currentRecord?.id"
              @click="doIntrospectCurrent"
              size="small"
            >
              拉取字段
            </el-button>
            <el-button
              type="primary"
              :icon="DocumentChecked"
              :disabled="!currentRecord?.id"
              @click="saveAllColumns"
              size="small"
            >
              保存配置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 主体内容区域 -->
      <div class="config-container h-full">
        <!-- 导航标签区域 - 使用el-tabs -->
        <div class="config-nav-tabs">
          <el-tabs v-model="activeTab" class="full-width-tabs">
        <el-tab-pane label="字段配置" name="fields">
              <template #label>
                <span class="tab-label">
                  <i class="fas fa-table"></i>
                  字段配置
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="基础设置" name="basic">
              <template #label>
                <span class="tab-label">
                  <i class="fas fa-cog"></i>
                  基础设置
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
          </div>

        <!-- 内容区域 - 在标签下方 -->
        <div class="config-content-area flex-1 overflow-hidden">
          <!-- 字段配置面板 -->
          <div v-if="activeTab === 'fields'" class="fields-panel h-full p-6 overflow-hidden">
          <!-- 操作工具栏 -->
          <div class="toolbar bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
            <div class="flex items-center justify-between">
              <div class="toolbar-left flex items-center space-x-3">
                <el-button
                  type="primary"
                  :icon="Plus"
                  :disabled="!currentRecord?.id"
                  @click="addColumn"
                  size="small"
                >
                  新增字段
                </el-button>
                <el-button
                  :icon="Refresh"
                  :disabled="!currentRecord?.id"
                  @click="reloadColumns"
                  size="small"
                >
                  刷新
                </el-button>
                <el-divider direction="vertical" />
                <span class="text-sm text-gray-600">共 {{ columns.length }} 个字段</span>
              </div>
              <div class="toolbar-right">
                <el-input
                  v-model="columnFilter"
                  placeholder="搜索字段..."
                  size="small"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <i class="fas fa-search"></i>
              </template>
                </el-input>
              </div>
            </div>
          </div>
          <!-- 字段配置表格 -->
          <div class="fields-container flex-1 overflow-hidden">
            <div class="fields-table-wrapper bg-white rounded-lg shadow-sm border border-gray-200">
              <el-table
                :data="filteredColumns"
                v-loading="columnsLoading"
                class="fields-table"
                border
                stripe
                size="default"
                height="calc(100vh - 400px)"
              >
                <el-table-column type="index" label="#" width="60" align="center" />

                <el-table-column prop="columnName" label="数据库列名" min-width="150">
              <template #default="{ row }">
                    <el-input
                      v-model="row.columnName"
                      placeholder="column_name"
                      size="small"
                    />
              </template>
            </el-table-column>

                <el-table-column prop="propertyName" label="Java属性名" min-width="150">
              <template #default="{ row }">
                    <el-input
                      v-model="row.propertyName"
                      placeholder="propertyName"
                      size="small"
                    />
              </template>
            </el-table-column>

                <el-table-column prop="javaType" label="Java类型" min-width="140">
              <template #default="{ row }">
                    <el-select v-model="row.javaType" placeholder="类型" size="small" class="w-full">
                  <el-option label="String" value="String" />
                  <el-option label="Integer" value="Integer" />
                  <el-option label="Long" value="Long" />
                  <el-option label="BigDecimal" value="BigDecimal" />
                  <el-option label="LocalDateTime" value="LocalDateTime" />
                  <el-option label="LocalDate" value="LocalDate" />
                  <el-option label="LocalTime" value="LocalTime" />
                  <el-option label="Boolean" value="Boolean" />
                  <el-option label="Double" value="Double" />
                  <el-option label="Float" value="Float" />
                </el-select>
              </template>
            </el-table-column>

                <el-table-column prop="comment" label="字段注释" min-width="150">
              <template #default="{ row }">
                    <el-input
                      v-model="row.comment"
                      placeholder="字段说明"
                      size="small"
                    />
              </template>
            </el-table-column>

                <el-table-column label="字段属性" min-width="280" align="center">
              <template #default="{ row }">
                    <div class="field-attributes">
                      <div class="attr-row">
                    <el-checkbox v-model="row.isPk" size="small">主键</el-checkbox>
                    <el-checkbox v-model="row.nullable" size="small">可空</el-checkbox>
                    <el-checkbox v-model="row.isListCol" size="small">列表</el-checkbox>
                      </div>
                      <div class="attr-row mt-1">
                        <el-checkbox v-model="row.isFormField" size="small">表单</el-checkbox>
                    <el-checkbox v-model="row.isQueryCond" size="small">查询</el-checkbox>
                        <el-select
                          v-if="row.isQueryCond"
                          v-model="row.queryType"
                          size="small"
                          placeholder="方式"
                          style="width: 70px; margin-left: 4px"
                          @change="updateQueryBehavior(row)"
                        >
                          <el-option label="精确" value="eq" />
                          <el-option label="模糊" value="like" />
                          <el-option label="范围" value="between" />
                        </el-select>
                  </div>
                </div>
              </template>
            </el-table-column>

                <el-table-column label="UI组件" min-width="180">
              <template #default="{ row }">
                    <div class="ui-config">
                      <el-select v-model="row.uiComponent" size="small" placeholder="组件" class="mb-1">
                  <el-option label="输入框" value="input" />
                  <el-option label="下拉框" value="select" />
                  <el-option label="日期" value="date" />
                  <el-option label="时间" value="datetime" />
                  <el-option label="数字" value="number" />
                  <el-option label="开关" value="switch" />
                  <el-option label="文本域" value="textarea" />
                </el-select>
                      <el-input
                        v-if="row.uiComponent === 'select'"
                        v-model="row.dictCode"
                        size="small"
                        placeholder="字典编码"
                      />
                    </div>
              </template>
            </el-table-column>

                <el-table-column label="操作" width="80" align="center" fixed="right">
              <template #default="{ row }">
                    <el-button
                      type="danger"
                      size="small"
                      :icon="Delete"
                      circle
                      @click="removeColumn(row)"
                    />
              </template>
            </el-table-column>
          </el-table>
            </div>
          </div>
        </div>

          <!-- 基础配置面板 -->
          <div v-else-if="activeTab === 'basic'" class="basic-panel h-full p-6 overflow-y-auto">
            <div class="basic-config-container max-w-4xl mx-auto space-y-6">
            <el-form :model="formModel" label-width="120px">
            <el-form-item label="表名">
              <el-input v-model="formModel.tableName" placeholder="表名" readonly disabled />
              <div style="font-size: 12px; color: #999; margin-top: 4px;">数据库表名，不可修改</div>
            </el-form-item>
            <el-form-item label="模块">
              <el-input v-model="formModel.moduleName" placeholder="system" />
              <div style="font-size: 12px; color: #999; margin-top: 4px;">模块名会影响代码生成路径</div>
            </el-form-item>
            <el-form-item label="模板类型">
              <el-radio-group v-model="formModel.templateType">
                <el-radio label="single">单表</el-radio>
                <el-radio label="multi">多表关联</el-radio>
              </el-radio-group>
              <div style="font-size: 12px; color: #999; margin-top: 4px;">单表：生成基础CRUD；多表：支持关联查询</div>
            </el-form-item>
            <el-form-item label="实体名">
              <el-input v-model="formModel.entityName" placeholder="SysUser" @input="onEntityInput" />
              <div style="font-size: 12px; color: #999; margin-top: 4px;">Java实体类名，建议大驼峰命名</div>
            </el-form-item>
            <el-form-item label="基础包">
              <el-input v-model="formModel.basePackage" placeholder="com.kexio" />
              <div style="font-size: 12px; color: #999; margin-top: 4px;">代码生成的包路径前缀</div>
            </el-form-item>
            <el-form-item label="权限前缀">
              <el-input v-model="formModel.permissionPrefix" placeholder="system:user" />
              <div style="font-size: 12px; color: #999; margin-top: 4px;">权限标识前缀，如：system:user</div>
            </el-form-item>
            <el-form-item label="父菜单">
              <el-select v-model="formModel.parentMenuId" placeholder="选择父菜单" filterable clearable style="width: 240px" :loading="loadingMenus">
                <el-option v-for="menu in menuOptions" :key="menu.id" :label="menu.title" :value="menu.id" />
              </el-select>
              <div style="font-size: 12px; color: #999; margin-top: 4px;">生成的菜单将挂在此菜单下</div>
            </el-form-item>
            <el-form-item label="开启前端">
              <el-switch v-model="formModel.frontendEnabled" />
            </el-form-item>
            <el-form-item label="允许覆盖">
              <el-switch v-model="formModel.overwriteEnabled" />
            </el-form-item>
            <!-- 多表关联配置 (仅多表模板显示) -->
            <div v-if="formModel.templateType === 'multi'" class="config-card bg-white rounded-lg shadow-sm border border-gray-200">
              <div class="card-header bg-gradient-to-r from-purple-50 to-purple-100 border-b border-gray-200 px-6 py-4">
                <div class="flex items-center justify-between">
                  <div>
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                      <i class="fas fa-link mr-3 text-purple-600"></i>
                      关联配置
                    </h3>
                    <p class="text-sm text-gray-600 mt-1">配置主从表关联关系</p>
              </div>
                  <el-button type="primary" size="small" @click="addRelation">
                    <i class="fas fa-plus mr-2"></i>
                    新增关联
                  </el-button>
                </div>
              </div>
              <div class="card-body p-6">
                <div v-if="relations.length === 0" class="empty-state text-center py-8">
                  <i class="fas fa-table text-4xl text-gray-300 mb-4"></i>
                  <p class="text-gray-500 mb-4">暂无关联配置</p>
                  <el-button type="primary" @click="addRelation">添加第一个关联</el-button>
                </div>
                <div v-else class="relations-list space-y-4">
                  <div
                    v-for="(relation, index) in relations"
                    :key="index"
                    class="relation-item bg-gray-50 rounded-lg p-4 border border-gray-200"
                  >
                    <div class="flex items-center justify-between mb-4">
                      <span class="text-sm font-medium text-gray-700">关联 {{ index + 1 }}</span>
                      <el-button type="danger" size="small" @click="removeRelation(relation)">
                        <i class="fas fa-trash mr-1"></i>
                        删除
                      </el-button>
                    </div>
                    <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-5 gap-4">
                      <div>
                        <label class="field-label">子表</label>
                        <el-select v-model="relation.childTable" placeholder="选择子表" filterable clearable class="w-full">
                          <el-option v-for="table in dbTableOptions" :key="table" :label="table" :value="table" />
                    </el-select>
                      </div>
                      <div>
                        <label class="field-label">别名</label>
                        <el-input v-model="relation.alias" placeholder="如：u" />
                      </div>
                      <div>
                        <label class="field-label">主表主键</label>
                        <el-input v-model="relation.masterKey" placeholder="id" />
                      </div>
                      <div>
                        <label class="field-label">子表外键</label>
                        <el-input v-model="relation.foreignKey" placeholder="order_id" />
                      </div>
                      <div>
                        <label class="field-label">附加列</label>
                        <el-input v-model="relation.extraColumns" placeholder="u.name as userName" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 扩展配置卡片 -->
            <div class="config-card bg-white rounded-lg shadow-sm border border-gray-200">
              <div class="card-header bg-gradient-to-r from-orange-50 to-orange-100 border-b border-gray-200 px-6 py-4">
                <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                  <i class="fas fa-code mr-3 text-orange-600"></i>
                  扩展配置
                </h3>
                <p class="text-sm text-gray-600 mt-1">JSON格式的高级配置选项</p>
              </div>
              <div class="card-body p-6">
                <div class="form-group">
                  <label class="field-label">JSON配置</label>
              <el-input
                v-model="extJson"
                type="textarea"
                :rows="8"
                placeholder='{"joinDefs":[{"alias":"u","table":"sys_user","on":"t.user_id = u.id","columns":"u.username as username"}]}'
                    class="code-textarea"
                  />
                  <div class="field-hint">
                    <i class="fas fa-info-circle mr-1"></i>
                    用于多表模板的复杂关联配置：table.ext.joinDefs
                  </div>
                </div>
              </div>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-bar bg-white rounded-lg shadow-sm border border-gray-200 p-6">
              <div class="flex items-center justify-center space-x-4">
                <el-button type="primary" size="large" @click="submitForm">
                  <i class="fas fa-save mr-2"></i>
                  保存基本信息
                </el-button>
                <el-button type="success" size="large" @click="doRecommendConfig">
                  <i class="fas fa-magic mr-2"></i>
                  智能推荐
                </el-button>
                <el-button type="warning" size="large" @click="doValidateConfig">
                  <i class="fas fa-check-circle mr-2"></i>
                  配置校验
                </el-button>
              </div>
            </div>
            </el-form>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listGenTables, introspectColumns, validateQueryDefs, previewGenerate, doGenerate as genGenerate, saveGenTable, deleteGenTable, batchDeleteGenTables, listDbTables, listGenColumns, saveGenColumns, downloadZip as apiDownloadZip, generateToProject as apiGenerateToProject, batchGenerate, batchPreview, validateTableConfig, recommendConfig } from '@/api/gen'
import { menuApi } from '@/api/menu'
import { Plus, Refresh, Delete, DocumentChecked, Search } from '@element-plus/icons-vue'
import SystemTable from '@/components/SystemTable/index.vue'

const query = reactive({ current: 1, size: 10 })
const rows = ref<any[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const previewFiles = ref<any[]>([])
const activePreviewTab = ref('0')
const formVisible = ref(false)
const drawerVisible = ref(false)
const activeTab = ref<'fields'|'basic'>('fields')
const drawerTitle = ref('配置生成')
const currentRecord = ref<any>(null)
const columns = ref<any[]>([])
const columnsLoading = ref(false)
const addDialogVisible = ref(false)
const selectedTableName = ref('')
const confirmAdding = ref(false)
const columnFilter = ref('')
const searchForm = reactive({
  tableName: '',
  comment: '',
  moduleName: ''
})
const formModel = reactive<any>({ id: null, tableName: '', templateType: 'single', moduleName: '', entityName: '', basePackage: 'com.kexio', permissionPrefix: '', parentMenuId: '', frontendEnabled: true, overwriteEnabled: false, ext: null })
const extJson = ref<string>('')
const relations = ref<any[]>([])
const selection = ref<any[]>([])
const dbTableOptions = ref<string[]>([])
const loadingTables = ref(false)
const menuOptions = ref<any[]>([])
const loadingMenus = ref(false)
const entityTouched = ref(false)
// 移除调试用的本地 options
async function load() {
  loading.value = true
  try {
    const params = {
      current: query.current,
      size: query.size,
      ...searchForm
    }
    console.log('🔍 加载数据参数:', params)
    const resp: any = await listGenTables(params)
    console.log('📊 API响应数据:', resp)

    if (resp && resp.success) {
      rows.value = resp.data?.records || resp.data?.rows || resp.data?.list || []
    total.value = resp.data?.total || 0
      console.log('✅ 数据加载成功:', { rows: rows.value.length, total: total.value })
    } else {
      console.error('❌ API响应失败:', resp)
      rows.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('❌ 数据加载异常:', error)
    rows.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearch() {
  query.current = 1
  load()
}

// 重置搜索
function handleReset() {
  searchForm.tableName = ''
  searchForm.comment = ''
  searchForm.moduleName = ''
  query.current = 1
  load()
}

// 分页处理
function handlePageChange(current: number, size: number) {
  query.current = current
  query.size = size
  load()
}

function reset() {
  searchForm.tableName = ''
  searchForm.comment = ''
  searchForm.moduleName = ''
  query.current = 1
  query.size = 10
  load()
}

function openDrawer(row:any) {
  console.log('🔧 openDrawer called with row:', row)
  
  currentRecord.value = row
  
  // 同时初始化 formModel，确保切换到基础设置标签时有数据
  Object.assign(formModel, {
    id: row.id,
    tableName: row.tableName,
    templateType: row.templateType || 'single',
    moduleName: row.moduleName,
    entityName: row.entityName,
    basePackage: row.basePackage || 'com.kexio',
    permissionPrefix: row.permissionPrefix,
    parentMenuId: row.parentMenuId,
    frontendEnabled: row.frontendEnabled !== false,
    overwriteEnabled: row.overwriteEnabled === true,
    ext: row.ext
  })
  
  // 处理ext字段显示
  const extObject = row.ext || {}
  extJson.value = Object.keys(extObject).length > 0 ? JSON.stringify(extObject, null, 2) : ''
  relations.value = Array.isArray(extObject?.relations) ? JSON.parse(JSON.stringify(extObject.relations)) : []
  
  console.log('📝 formModel initialized:', JSON.parse(JSON.stringify(formModel)))
  
  drawerTitle.value = `配置：${row.tableName}`
  activeTab.value = 'fields'
  drawerVisible.value = true
  reloadColumns()
}

function onSelChange(sel:any[]) {
  selection.value = sel || []
}

async function openCreate() {
  selectedTableName.value = ''
  await ensureDbTablesLoaded()
  addDialogVisible.value = true
}

function openEdit(row:any) {
  console.log('🔍 openEdit called with row:', row)
  
  // 编辑基本信息改为使用抽屉的"基本信息"标签
  currentRecord.value = row

  // 后端现在自动返回JSON对象，直接使用即可
  Object.assign(formModel, {
    id: row.id,
    tableName: row.tableName,
    templateType: row.templateType || 'single',
    moduleName: row.moduleName,
    entityName: row.entityName,
    basePackage: row.basePackage || 'com.kexio',
    permissionPrefix: row.permissionPrefix,
    parentMenuId: row.parentMenuId,
    frontendEnabled: row.frontendEnabled !== false,
    overwriteEnabled: row.overwriteEnabled === true,
    ext: row.ext
  })
  
  console.log('📝 formModel after assign:', JSON.parse(JSON.stringify(formModel)))

  // 处理ext字段显示
  const extObject = row.ext || {}
  extJson.value = Object.keys(extObject).length > 0 ? JSON.stringify(extObject, null, 2) : ''
  relations.value = Array.isArray(extObject?.relations) ? JSON.parse(JSON.stringify(extObject.relations)) : []

  drawerTitle.value = `配置：${row.tableName}`
  activeTab.value = 'basic'
  drawerVisible.value = true
}

async function submitForm() {
  // 验证必要字段
  if (!formModel.tableName) {
    ElMessage.error('表名不能为空')
    return
  }
  if (!formModel.id) {
    ElMessage.error('记录ID不能为空')
    return
  }
  
  // 后端现在支持自动JSON转换，直接发送对象即可
  const payload = { ...formModel }

  let extObject: any = {}
  if (extJson.value && extJson.value.trim().length) {
    try { extObject = JSON.parse(extJson.value) } catch (e) { ElMessage.error('扩展配置JSON不合法'); return }
  }

  if (relations.value.length) {
    extObject.relations = relations.value.map((r:any)=>({
      alias: r.alias,
      table: r.childTable,
      columns: r.masterKey && r.foreignKey ? `${r.foreignKey},${r.extraColumns||''}`.replace(/,+$/,'') : (r.extraColumns||''),
      values: r.masterKey && r.foreignKey ? `#{mainId},${r.extraColumns? r.extraColumns.replace(/(\w+)/g,'#{data.$1}') : ''}`.replace(/,\s*$/,'') : (r.values||''),
      where: r.masterKey && r.foreignKey ? `${r.foreignKey} = \\#{mainId}` : (r.where||'')
    }))
  }

  // 直接设置对象，后端会自动处理JSON转换
  payload.ext = Object.keys(extObject).length > 0 ? extObject : null

  const resp: any = await saveGenTable(payload)
  if (resp && resp.success) {
    ElMessage.success('保存成功')
    formVisible.value = false
    await load()
    // 新增后自动为该表拉取字段
    const just = rows.value.find((r:any)=> r.tableName === formModel.tableName && r.moduleName === formModel.moduleName)
    if (just && just.id) {
      const intro: any = await introspectColumns(just.id)
      if (intro && intro.success) {
        ElMessage.success('已拉取字段')
      }
    }
  } else {
    ElMessage.error(resp?.message || '保存失败')
  }
}

async function confirmAdd() {
  if (confirmAdding.value) return
  const tbl = selectedTableName.value
  if (!tbl) {
    ElMessage.warning('请选择表名')
    return
  }
  confirmAdding.value = true
  const moduleName = 'system'
  const entity = toPascalCase(tbl)
  const prefix = `${moduleName}:${String(tbl).replace(/[_\-\s]+/g, ' ').trim().split(' ').join(':').toLowerCase()}`
  const payload = { tableName: tbl, templateType: 'single', moduleName, entityName: entity, basePackage: 'com.kexio', permissionPrefix: prefix, frontendEnabled: true, overwriteEnabled: false }
  try {
    const resp: any = await saveGenTable(payload)
    if (resp && resp.success) {
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      await load()
      const just = rows.value.find((r:any)=> r.tableName === tbl && r.moduleName === moduleName)
      if (just && just.id) {
        const intro: any = await introspectColumns(just.id)
        if (intro && intro.success) {
          ElMessage.success('已拉取字段')
        }
      }
    } else {
      ElMessage.error(resp?.message || '新增失败')
    }
  } catch (e:any) {
    ElMessage.error(e?.message || '新增失败')
  } finally {
    confirmAdding.value = false
  }
}

async function remove(row:any) {
  await deleteGenTable(row.id)
  ElMessage.success('删除成功')
  load()
}

async function reloadColumns() {
  if (!currentRecord.value?.id) return
  columnsLoading.value = true
  try {
    const resp: any = await listGenColumns(currentRecord.value.id)
    // 后端现在自动返回JSON对象，无需手动解析
    columns.value = (Array.isArray(resp?.data) ? resp.data : []).map((col: any) => {
      // 处理查询行为配置
      if (col.queryBehavior) {
        try {
          const behavior = typeof col.queryBehavior === 'string'
            ? JSON.parse(col.queryBehavior)
            : col.queryBehavior
          col.queryType = behavior.type || 'eq'
        } catch {
          col.queryType = 'eq'
        }
      } else {
        col.queryType = 'eq'
      }

      // 确保必要字段有默认值
      col.isListCol = col.isListCol ?? true
      col.isFormField = col.isFormField ?? true
      col.isQueryCond = col.isQueryCond ?? false
      col.dictCode = col.dictCode || ''

      return col
    })
  } finally {
    columnsLoading.value = false
  }
}

async function saveAllColumns() {
  if (!currentRecord.value?.id) return

  // 保存前处理查询行为配置
  const processedColumns = columns.value.map(col => {
    const processed = { ...col }

    // 处理查询行为
    if (processed.isQueryCond && processed.queryType) {
      processed.queryBehavior = JSON.stringify({ type: processed.queryType })
    } else {
      processed.queryBehavior = null
    }

    // 清理临时字段
    delete processed.queryType

    return processed
  })

  // 后端现在支持自动JSON转换，直接发送处理后的数据
  const resp: any = await saveGenColumns(currentRecord.value.id, processedColumns)
  if (resp && resp.success) ElMessage.success('字段已保存')
}

async function addColumn() {
  columns.value.push({
    columnName: '',
    propertyName: '',
    jdbcType: '',
    javaType: '',
    comment: '',
    isListCol: true,
    isFormField: true,
    isQueryCond: false,
    queryType: 'eq',
    uiComponent: 'input',
    dictCode: ''
  })
}

// 更新查询行为
function updateQueryBehavior(row: any) {
  if (row.isQueryCond && row.queryType) {
    row.queryBehavior = JSON.stringify({ type: row.queryType })
  } else {
    row.queryBehavior = null
  }
}

async function removeColumn(row:any) {
  const idx = columns.value.indexOf(row)
  if (idx >= 0) columns.value.splice(idx, 1)
}

// 过滤字段列表
const filteredColumns = computed(() => {
  if (!columnFilter.value) return columns.value
  const filter = columnFilter.value.toLowerCase()
  return columns.value.filter(col =>
    col.columnName?.toLowerCase().includes(filter) ||
    col.propertyName?.toLowerCase().includes(filter) ||
    col.comment?.toLowerCase().includes(filter)
  )
})

// 关联表管理函数
function addRelation() {
  relations.value.push({
    childTable: '',
    alias: '',
    masterKey: 'id',
    foreignKey: '',
    extraColumns: ''
  })
}

function removeRelation(row: any) {
  const idx = relations.value.indexOf(row)
  if (idx >= 0) relations.value.splice(idx, 1)
}

async function doIntrospectCurrent() {
  if (!currentRecord.value?.id) return
  const resp: any = await introspectColumns(currentRecord.value.id)
  if (resp && resp.success) {
    ElMessage.success('已拉取缺失字段')
    reloadColumns()
  }
}

onMounted(async () => {
  await ensureDbTablesLoaded()
  await ensureMenusLoaded()
})

async function ensureDbTablesLoaded() {
  if (dbTableOptions.value.length) return
  loadingTables.value = true
  try {
    const resp: any = await listDbTables()
    const arr: any[] = Array.isArray(resp?.data) ? resp.data : []
    dbTableOptions.value = arr as string[]
  } finally {
    loadingTables.value = false
  }
}

async function ensureMenusLoaded() {
  if (menuOptions.value.length) return
  loadingMenus.value = true
  try {
    const resp: any = await menuApi.getMenusByType('DIR') // 只加载目录类型的菜单
    const arr: any[] = Array.isArray(resp?.data) ? resp.data : []
    menuOptions.value = arr.map((menu: any) => ({
      id: menu.id,
      title: menu.title || menu.name,
      name: menu.name
    }))
    // 添加默认选项
    if (!menuOptions.value.find(m => m.id === 'menu_system')) {
      menuOptions.value.unshift({ id: 'menu_system', title: '系统管理', name: 'system' })
    }
  } catch (e) {
    console.warn('加载菜单失败:', e)
    // 提供默认选项
    menuOptions.value = [
      { id: 'menu_system', title: '系统管理', name: 'system' }
    ]
  } finally {
    loadingMenus.value = false
  }
}

function toPascalCase(name: string): string {
  if (!name) return ''
  return name
    .replace(/[_\-\s]+/g, ' ')
    .trim()
    .split(' ')
    .filter(Boolean)
    .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
    .join('')
}

function onEntityInput() {
  entityTouched.value = true
}

watch(() => formModel.tableName, (val) => {
  if (val && !entityTouched.value) {
    formModel.entityName = toPascalCase(String(val))
    // 智能生成权限前缀
    if (!formModel.permissionPrefix) {
      const cleanName = String(val)
        .replace(/^(tb_|t_|sys_|gen_)/, '') // 移除常见表前缀
        .replace(/[_\-\s]+/g, '') // 移除分隔符
        .toLowerCase()
      formModel.permissionPrefix = `${formModel.moduleName || 'system'}:${cleanName}`
    }
  }
})

// 智能推荐模板类型
watch(() => formModel.tableName, (val) => {
  if (val) {
    // 根据表名智能推荐模板类型
    const tableName = String(val).toLowerCase()
    if (tableName.includes('_rel_') || tableName.includes('_relation_')) {
      formModel.templateType = 'multi'
    } else {
      formModel.templateType = 'single'
    }
  }
})

async function batchRemove() {
  const ids = selection.value.map((x:any)=>x.id)
  if (!ids.length) return
  await batchDeleteGenTables(ids)
  ElMessage.success('已删除')
  load()
}

async function doIntrospect(row:any) {
  const resp: any = await introspectColumns(row.id)
  if (resp?.success) ElMessage.success(String(resp.data || resp.message))
  else ElMessage.error(resp?.message || '拉取失败')
}

async function doValidate(row:any) {
  const resp: any = await validateQueryDefs(row.id)
  if (resp?.success) ElMessage.success('校验通过')
  else ElMessage.error(resp?.message || '校验失败')
}

async function doPreview(row:any) {
  const resp: any = await previewGenerate(row.id)
  if (resp && resp.success) {
    previewFiles.value = Array.isArray(resp.data?.files) ? resp.data.files : []
    activePreviewTab.value = '0'
    dialogVisible.value = true
  }
}

function fileLabel(f: any): string {
  // 如果是批量预览，显示表名+文件名
  if (f.tableName && f.displayPath) {
    const fileName = f.displayPath.split('/').pop() || f.displayPath
    return `${f.tableName}/${fileName}`
  }

  const p = String(f?.path || '')
  if (!p) return ''
  const idx1 = p.lastIndexOf('/')
  const idx2 = p.lastIndexOf('\\')
  const idx = Math.max(idx1, idx2)
  return idx >= 0 ? p.slice(idx + 1) : p
}

async function executeGenerate(row:any) {
  const resp: any = await genGenerate(row.id)
  if (resp?.success) ElMessage.success('已提交生成')
  else ElMessage.error(resp?.message || '生成失败')
}

async function downloadZip(row:any) {
  try {
    const resp: any = await apiDownloadZip(row.id)

    // 创建下载链接
    const blob = new Blob([resp], { type: 'application/zip' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${row.moduleName}-${row.entityName}-code.zip`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('代码包下载成功')
  } catch (error: any) {
    ElMessage.error('下载失败: ' + (error.message || '未知错误'))
  }
}

async function generateToProject(row:any) {
  try {
    // 弹出确认对话框选择目标模块
    const { value: targetModule } = await ElMessageBox.prompt(
      '请输入目标模块名（如：kexio-user-management）：',
      '生成到项目模块',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: row.moduleName,
        inputValue: `kexio-${row.moduleName}-management`
      }
    )

    if (!targetModule) {
      ElMessage.warning('请输入目标模块名')
      return
    }

    const resp: any = await apiGenerateToProject(row.id, {
      targetModule: targetModule,
      overwrite: false
    })

    if (resp?.success) {
      ElMessage.success(`代码已生成到模块：${targetModule}`)
    } else {
      ElMessage.error(resp?.message || '生成到项目失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

async function doBatchPreview() {
  if (!selection.value.length) {
    ElMessage.warning('请先选择要预览的表')
    return
  }

  try {
    const ids = selection.value.map(row => row.id)
    const resp: any = await batchPreview(ids)

    if (resp?.success) {
      // 展示批量预览结果
      const results = resp.data?.results || {}
      const errors = resp.data?.errors || []

      if (errors.length > 0) {
        ElMessage.warning(`部分表预览失败：${errors.join(', ')}`)
      }

      // 合并所有预览文件
      const allFiles: any[] = []
      Object.keys(results).forEach(tableName => {
        const files = results[tableName] || []
        files.forEach((file: any) => {
          allFiles.push({
            ...file,
            tableName: tableName,
            displayPath: `${tableName}/${file.path}`
          })
        })
      })

      previewFiles.value = allFiles
      activePreviewTab.value = '0'
      dialogVisible.value = true

      ElMessage.success(`批量预览完成，共${Object.keys(results).length}个表`)
    } else {
      ElMessage.error(resp?.message || '批量预览失败')
    }
  } catch (error: any) {
    ElMessage.error('批量预览失败: ' + (error.message || '未知错误'))
  }
}

async function doBatchGenerate() {
  if (!selection.value.length) {
    ElMessage.warning('请先选择要生成的表')
    return
  }

  try {
    const ids = selection.value.map(row => row.id)
    const resp: any = await batchGenerate(ids)

    if (resp?.success) {
      const { successCount, totalCount, errors } = resp.data || {}

      if (errors && errors.length > 0) {
        ElMessage.warning(`批量生成完成：成功${successCount}个，失败${errors.length}个。失败详情：${errors.join(', ')}`)
      } else {
        ElMessage.success(`批量生成完成：共成功生成${successCount}/${totalCount}个表`)
      }
    } else {
      ElMessage.error(resp?.message || '批量生成失败')
    }
  } catch (error: any) {
    ElMessage.error('批量生成失败: ' + (error.message || '未知错误'))
  }
}

async function doRecommendConfig() {
  if (!formModel.tableName) {
    ElMessage.warning('请先输入表名')
    return
  }

  try {
    const resp: any = await recommendConfig({
      tableName: formModel.tableName,
      columns: columns.value
    })

    if (resp?.success) {
      const recommendation = resp.data

      // 询问用户是否应用推荐配置
      const confirmed = await ElMessageBox.confirm(
        `智能推荐结果：
        模块名：${recommendation.moduleName}
        实体名：${recommendation.entityName}
        权限前缀：${recommendation.permissionPrefix}
        模板类型：${recommendation.templateType}

        是否应用这些推荐配置？`,
        '智能推荐',
        {
          confirmButtonText: '应用推荐',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).catch(() => false)

      if (confirmed) {
        // 应用推荐配置
        formModel.moduleName = recommendation.moduleName
        formModel.entityName = recommendation.entityName
        formModel.permissionPrefix = recommendation.permissionPrefix
        formModel.templateType = recommendation.templateType

        // 应用UI组件推荐
        if (recommendation.uiRecommendations) {
          columns.value.forEach(column => {
            const recommended = recommendation.uiRecommendations[column.propertyName]
            if (recommended) {
              column.uiComponent = recommended
            }
          })
        }

        ElMessage.success('已应用智能推荐配置')
      }
    } else {
      ElMessage.error(resp?.message || '获取推荐配置失败')
    }
  } catch (error: any) {
    if (error !== false) { // 不是用户取消
      ElMessage.error('智能推荐失败: ' + (error.message || '未知错误'))
    }
  }
}

async function doValidateConfig() {
  if (!currentRecord.value?.id) {
    ElMessage.warning('请先保存基本配置')
    return
  }

  try {
    const resp: any = await validateTableConfig(currentRecord.value.id)

    if (resp?.success) {
      const { hasErrors, errors, warnings } = resp.data

      let message = '配置校验结果：\n\n'

      if (hasErrors) {
        message += '❌ 错误：\n' + errors.join('\n') + '\n\n'
      }

      if (warnings.length > 0) {
        message += '⚠️ 警告：\n' + warnings.join('\n') + '\n\n'
      }

      if (!hasErrors && warnings.length === 0) {
        message += '✅ 配置校验通过，没有发现问题！'
        ElMessage.success('配置校验通过')
      } else {
        await ElMessageBox.alert(message, '配置校验结果', {
          confirmButtonText: '确定',
          type: hasErrors ? 'error' : 'warning'
        })
      }
    } else {
      ElMessage.error(resp?.message || '配置校验失败')
    }
  } catch (error: any) {
    ElMessage.error('配置校验失败: ' + (error.message || '未知错误'))
  }
}

load()
</script>

<style lang="scss" scoped>
.gen-config-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 120px);
  }
}

.config-container {
  height: 100%;
  background: #f5f7fa;
}

.config-header {
  background: white;
  border-bottom: 1px solid #e5e7eb;

  .header-left {
    .el-tag {
      font-family: 'Monaco', 'Menlo', monospace;
    }
  }
}

/* 配置弹窗tabs样式 - 保持默认布局 */
.config-nav-tabs {
  background: #f8f9fa;
  padding: 16px 24px 0;
  
  .full-width-tabs {
    // 隐藏tabs的内容区域（我们自己控制显示）
    :deep(.el-tabs__content) {
      display: none !important;
    }
  }
}

.tab-label {
  display: flex;
  align-items: center;
  justify-content: center;

  i {
    margin-right: 6px;
    font-size: 14px;
  }
}

.config-content-area {
  flex: 1;
  background: #f8f9fa;
}

.fields-panel, .basic-panel {
  .toolbar {
    .toolbar-left {
      .el-button {
        border-radius: 6px;
      }
    }
  }

  .fields-table-wrapper {
    .fields-table {
      .field-attributes {
        .attr-row {
          display: flex;
          gap: 8px;
          align-items: center;

          .el-checkbox {
            margin-right: 8px;

            :deep(.el-checkbox__label) {
              font-size: 12px;
              padding-left: 4px;
            }
          }
        }
      }

      .ui-config {
        display: flex;
        flex-direction: column;
        gap: 4px;
      }
    }
  }
}

.basic-panel {
  .config-card {
    .card-header {
      h3 {
        margin: 0;
      }
    }

    .card-body {
      .form-group {
        .field-label {
          display: block;
          font-size: 14px;
          font-weight: 500;
          color: #374151;
          margin-bottom: 8px;
        }

        .field-hint {
          font-size: 12px;
          color: #6b7280;
          margin-top: 4px;
        }

        .readonly-input {
          :deep(.el-input__inner) {
            background-color: #f9fafb;
            color: #6b7280;
          }
        }
      }

      .template-radio-group {
        width: 100%;

        :deep(.el-radio-button__inner) {
          padding: 12px 20px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

      .switches-group {
        .switch-item {
          background: #f8fafc;
          border-radius: 8px;
          padding: 12px 16px;
          border: 1px solid #e2e8f0;

          :deep(.el-switch__label) {
            color: #4a5568;
            font-weight: 500;
          }
        }
      }

      .relation-item {
        .field-label {
          font-size: 12px;
          color: #6b7280;
          margin-bottom: 4px;
        }
      }

      .code-textarea {
        :deep(.el-textarea__inner) {
          font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
          font-size: 13px;
          line-height: 1.5;
        }
      }
    }
  }

  .action-bar {
    margin-top: 24px;

    .el-button {
      padding: 12px 24px;
      font-weight: 500;
    }
  }

  .empty-state {
    i {
      opacity: 0.6;
    }
  }
}

// 主页样式
.gen-page {
  .page-header {
    .search-form {
      .search-form-inline {
        .search-form-item {
          margin-right: 24px;
          margin-bottom: 16px;

          :deep(.el-form-item__label) {
            width: auto;
            min-width: 60px;
            font-weight: 500;
            color: #606266;
          }

          :deep(.el-form-item__content) {
            margin-left: 8px;
          }
        }

        .search-form-buttons {
          margin-left: 16px;

          :deep(.el-form-item__content) {
            display: flex;
            gap: 8px;
          }
        }
      }
    }
  }

  .batch-toolbar {
    border-left: 4px solid #409eff;

    .text-primary {
      color: #409eff;
    }
  }

  .table-actions {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;

    .el-button {
      padding: 4px 8px;
      font-size: 12px;

      i {
        font-size: 12px;
      }
    }

    .el-dropdown {
      .el-button {
        padding: 4px 8px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .config-header {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 12px;

    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .basic-panel .config-card .card-body {
    .grid {
      grid-template-columns: 1fr;
    }
  }

  .gen-page {
    .page-header {
      .search-form {
        .search-form-inline {
          flex-direction: column;

          .search-form-item {
            margin-right: 0;
            margin-bottom: 12px;

            :deep(.el-form-item__content) {
              margin-left: 0;
              margin-top: 4px;

              .el-input {
                width: 100% !important;
              }
            }
          }

          .search-form-buttons {
            margin-left: 0;
            margin-top: 8px;

            :deep(.el-form-item__content) {
              justify-content: flex-start;
            }
          }
        }
      }

      .flex {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;
      }
    }

    .batch-toolbar {
      .flex {
        flex-direction: column;
        gap: 12px;

        &:first-child {
          align-items: stretch;
        }
      }
    }

    .table-actions {
      flex-direction: column;
      gap: 2px;

      .el-button, .el-dropdown .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>


